package com.shop.service.module.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.service.module.entity.Result;
import com.shop.service.module.entity.UserEntity;
import com.shop.service.module.feign.TokenService;
import com.shop.service.module.mapper.UserMapper;
import com.shop.service.module.service.ShopUserService;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class ShopUserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements ShopUserService {
    @Autowired
    private TokenService tokenService;

    @Override
    public Result getListForPage(Integer pno, Integer psize, String username, Integer freeze, String phone, String beginTime, String endTime) throws ParseException {
        //创建分页对象
        Page<UserEntity> page = new Page<>(pno, psize);
        //编写查询条件
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("type", 1);
        if (!StringUtils.isEmpty(phone)) {
            queryWrapper.like("phone", phone);
        }
        if (!StringUtils.isEmpty(username)) {
            queryWrapper.like("username", username);
        }
        if (freeze != null) {
            queryWrapper.eq("freeze", freeze);
        }


        if (!StringUtils.isEmpty(beginTime)) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date beginDate = simpleDateFormat.parse(beginTime + " 00:00:00");
            Date endDate = simpleDateFormat.parse(endTime + " 23:59:59");
            queryWrapper.ge("insert_time", beginDate);
            queryWrapper.le("insert_time", endDate);

        }
        queryWrapper.orderByDesc("insert_time");
        Page result = baseMapper.selectPage(page, queryWrapper);
        //声明返回结果的json对象
        JSONObject data = new JSONObject();
        //将list列表放入返回data的list属性中
        data.put("list", result.getRecords());
        //定义page属性的对象
        JSONObject jsonObjectPage = new JSONObject();
        //将页号放入page属性的pno中
        jsonObjectPage.put("pno", pno);
        //将每页多少条放入page属性的psize中
        jsonObjectPage.put("psize", psize);
        //将共多少页放入page属性的pCount中
        jsonObjectPage.put("pCount", result.getPages());
        //将共多少条数据放入到page属性的totalElements中
        jsonObjectPage.put("totalElements", result.getTotal());
        //将page对象放入data的page属性中
        data.put("page", jsonObjectPage);
        return Result.end(200, data, "查询成功");
    }

    @Override
    public Result insert(UserEntity userEntity) {
        if (StringUtils.isEmpty(userEntity.getUsername())) {
            return Result.end(500, "", "账号不能为空");
        }
        if (StringUtils.isEmpty(userEntity.getPassword())) {
            return Result.end(500, "", "密码不能为空");
        }
        if (StringUtils.isEmpty(userEntity.getNickname())) {
            return Result.end(500, "", "昵称不能为空");
        }
        if (StringUtils.isEmpty(userEntity.getPhone())) {
            return Result.end(500, "", "手机号不能为空");
        }
        if (StringUtils.isEmpty(userEntity.getSex())) {
            return Result.end(500, "", "性别不能为空");
        }
        if (StringUtils.isEmpty(userEntity.getFace())) {
            return Result.end(500, "", "头像不能为空");
        }
        //判断用户名和手机号是否重复
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", userEntity.getUsername())
                .or().eq("phone", userEntity.getPhone());
        List<UserEntity> list = baseMapper.selectList(queryWrapper);
        //如果集合的长度为0则说明用户名和手机号不重复
        if (list.size() == 0) {

            userEntity
                    //设置冻结状态
                    .setFreeze(0)
                    //设置创建时间
                    .setInsertTime(new Date())
                    //设置账号类别
                    .setType(1);
            //将密码进行加密
            String encode = new BCryptPasswordEncoder().encode(userEntity.getPassword());
            userEntity.setPassword(encode);
            int result = baseMapper.insert(userEntity);
            if (result > 0) {
                return Result.end(200, "", "插入成功");
            } else {
                return Result.end(500, "", "插入失败");

            }
        } else {
            return Result.end(500, "", "用户名或手机号已存在");
        }


    }

    @Override
    public Result loginPassword(String username, String password) {
        //查询用户
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("type", "1");
        queryWrapper.eq("username", username);
        List<UserEntity> userEntities = baseMapper.selectList(queryWrapper);
        UserEntity user = userEntities.get(0);

        if (user == null) {
            return Result.end(500, "", "账号或密码不正确");
        }
        String passwordEncoded = user.getPassword();
        //创建密码加密类
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(password, passwordEncoded)) {
            return Result.end(500, "", "用户或密码错误");
        }
        if (user.getFreeze() == 1) {
            return Result.end(500, "", "您的账号已经被冻结暂时无法登录");
        }
        String token = tokenService.getToken(username,
                password,
                "password",
                "client_2",
                "123456",
                "client_2");
        JSONObject jsonObject = JSONObject.parseObject(token);
        if ("500".equals(jsonObject.get("code"))) {
            return Result.end(500, "", "用户鉴权失败");
        }
        JSONObject data = new JSONObject();
        data.put("userInfo", user);
        data.put("jwt", jsonObject);
        return Result.end(200, data, "登陆成功");


    }

    @Override
    public Result register(String username, String password) {
        //查询用户
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("type", "1");
        queryWrapper.eq("username", username);
        List<UserEntity> userEntities = baseMapper.selectList(queryWrapper);


        if (userEntities.size() != 0) {
            return Result.end(500, "", "账号已存在");
        }
        UserEntity user=new UserEntity();
        user=new UserEntity();
        //设置手机号码为账号
        user.setPhone(username);
        //设置用户账号为账号
        user.setUsername(username);
        //设置用户密码为加密结果
        user.setPassword(new BCryptPasswordEncoder().encode(password));
        //设置注册时间
        user.setInsertTime(new Date());
        //设置用户类型为商城会员
        user.setType(1);
        //设置用户为未冻结状态
        user.setFreeze(0);
        //执行插入操作，并根据返回结果决定用户是否成功
        int updateCount =baseMapper.insert(user);
        if(updateCount>0){
            return Result.end(200,"","注册成功");
        }else{
            return Result.end(500,"","注册失败");
        }


    }
}
